package io.zim.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.zim.common.annotation.DataFilter;
import io.zim.common.exception.RRException;
import io.zim.common.utils.Constant;
import io.zim.common.utils.PageUtils;
import io.zim.common.utils.Query;
import io.zim.modules.sys.dao.SysUserDao;
import io.zim.modules.sys.entity.SysUserEntity;
import io.zim.modules.sys.service.SysRoleService;
import io.zim.modules.sys.service.SysUserRoleService;
import io.zim.modules.sys.service.SysUserService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;

import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


/**
 * 系统用户
 * 
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年9月18日 上午9:46:09
 * extends ServiceImpl<SysUserDao, SysUserEntity>
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {
	@Autowired
	private SysUserRoleService sysUserRoleService;
	@Autowired
	private SysRoleService sysRoleService;

	@Override
	public List<String> queryAllPerms(Long userId) {
		return baseMapper.queryAllPerms(userId);
	}

	@Override
	public List<Long> queryAllMenuId(Long userId) {
		return baseMapper.queryAllMenuId(userId);
	}

	@Override
	public SysUserEntity queryByUserName(String username) {
		return baseMapper.queryByUserName(username);
	}

	@Override
	public boolean updatePassword(Long userId, String password, String newPassword) {
		SysUserEntity userEntity = new SysUserEntity();
		userEntity.setPassword(newPassword);
		return this.update(userEntity,
				new UpdateWrapper<SysUserEntity>().eq("user_id", userId).eq("password", password));
	}

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		String username = (String)params.get("username");
		Long createUserId = (Long)params.get("createUserId");

		Page<SysUserEntity> page = (Page<SysUserEntity>) this.page(
				new Query<SysUserEntity>(params).getPage(),
				new QueryWrapper<SysUserEntity>()
						.like(StringUtils.isNotBlank(username),"username", username)
						.eq(createUserId != null,"create_user_id", createUserId)
		);
		return new PageUtils(page);
	}

	@Override
	@Transactional
	public boolean insert(SysUserEntity user) {
		user.setCreateTime(new Date());
		//sha256加密
		String salt = RandomStringUtils.randomAlphanumeric(20);
		user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex());
		user.setSalt(salt);
		boolean isOk = this.save(user);

		//检查角色是否越权
		checkRole(user);
		
		//保存用户与角色关系
		sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
		return isOk;
	}

	@Override
	@Transactional
	public boolean update(SysUserEntity user) {
		if (StringUtils.isBlank(user.getPassword())) {
			user.setPassword(null);
		 } else {
			user.setPassword(new Sha256Hash(user.getPassword(), user.getSalt()).toHex());
		}
		boolean isOk = this.updateById(user);
		
		//检查角色是否越权
		checkRole(user);
		
		//保存用户与角色关系
		sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
		return isOk;
	}

	@Override
	public int deleteByIds(Long[] userId) {
		return baseMapper.deleteBatch(userId);
	}

	@Override
	@DataFilter(userAlias = "u.user_id", deptAlias = "u.dept_id", self = false)
	public List<SysUserEntity> queryList(Map<String, Object> map){
		return baseMapper.queryList(map);
	}

	@Override
	@DataFilter(userAlias = "u.user_id", deptAlias = "u.dept_id", self = false)
	public int queryTotal(Map<String, Object> map) {
		return baseMapper.queryTotal(map);
	}

	/**
	 * 检查角色是否越权
	 */
	private void checkRole(SysUserEntity user){
		if (user.getRoleIdList() == null || user.getRoleIdList().size() == 0) {
			return;
		}
		//如果不是超级管理员，则需要判断用户的角色是否自己创建
		if (user.getCreateUserId() == Constant.SUPER_ADMIN) {
			return ;
		}
		
		//查询用户创建的角色列表
		List<Long> roleIdList = sysRoleService.queryRoleIdList(user.getCreateUserId());

		//判断是否越权
		if (!roleIdList.containsAll(user.getRoleIdList())) {
			throw new RRException("新增用户所选角色，不是本人创建");
		}
	}
}
